Memcached is a distributed, high-speed caching system that stores simple key-value pairs in memory. It’s ideal for quick, transient data storage without persistence or complex features.
Redis is a distributed, open-source, in-memory data store used as a cache, database, and message broker. It supports advanced data structures and features like persistence, replication, and clustering.
You can configure IDistributedCache in .NET to use either Redis , Memcached or Sql Server as the backend cache provider. This allows you to use the distributed caching infrastructure of .NET while leveraging the power of Redis or Memcached to store the data.
Using Redis with IDistributedCache
- Install the Redis package:
dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
- Configure Redis in Program.cs or Startup.cs:
// Add Redis configuration builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; options.InstanceName = "MyAppCache:"; }); //------------------------------- // A simple route to use the distributed cache app.MapGet("/", async (IDistributedCache cache) => { string key = "user:1"; string value = await cache.GetAsync(key); if (value == null) { value = "John Doe"; await cache.SetAsync(key, value, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60) }); } return value; });
Using Memcached with IDistributedCache
- Install the EnyimMemcached package:
dotnet add package EnyimMemcachedCore
- You will need to implement this yourself or use a third-party library that provides the necessary functionality.( very basic custom implementation of IDistributedCache for Memcached)
using Enyim.Caching; using Microsoft.Extensions.Caching.Distributed; public class MemcachedDistributedCache(IMemcachedClient _memcachedClient) : IDistributedCache { public byte[]? Get(string key) { return _memcachedClient.Get< byte[]>(key); } public async Task<byte[]?> GetAsync(string key, CancellationToken token = default) { var value =await _memcachedClient.GetAsync<byte[]>(key); return value.Success ? value.Value : null; } public void Refresh(string key) { } public Task RefreshAsync(string key, CancellationToken token = default) { return Task.CompletedTask; } public void Remove(string key) { _memcachedClient.Remove(key); } public async Task RemoveAsync(string key, CancellationToken token = default) { await _memcachedClient.RemoveAsync(key); } public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { _memcachedClient.Set(key, value, options.AbsoluteExpirationRelativeToNow ?? TimeSpan.FromMinutes(60)); } public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) { await _memcachedClient.SetAsync(key, value, options.AbsoluteExpirationRelativeToNow ?? TimeSpan.FromMinutes(60)); } }
- Configure Memcached in Program.cs (via a custom implementation of IDistributedCache):
builder.Services.AddEnyimMemcached(x => { x.Servers.Add( new Server { Address = "localhost", Port = 1111 }); //Memcached server address }); builder.Services.AddSingleton<IDistributedCache, MemcachedDistributedCache>(); //------------------------------- app.MapGet("/", async (IDistributedCache cache) => { string key = "user:1"; string value = await cache.GetStringAsync(key); if (value == null) { value = "John Doe"; // Default value await cache.SetAsync(key, value, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }); } return value; });
Using SqlServer with IDistributedCache
Install the dotnet tool:
dotnet tool install --global dotnet-sql-cache
Use this tool to create the required Cache table in SQL Server Database:
dotnet sql-cache create "--Connection String--" dbo CacheTable
Configure SqlServer in Program.cs :
builder.Services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = “--Connection String--";
options.SchemaName = “cache";
options.TableName = “MyCacheTable";
});
Using IDistributedCache
depends on the configuration and can be backed by either Memcache, Redis or SQL Server
app.MapGet("/", async (IDistributedCache cache) =>
{
string key = "user:1";
string value = await cache.GetStringAsync(key);
if (value == null)
{
value = "John Doe";
await cache.SetStringAsync(key, value, new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60)
});
}
return value;
});